package com.stylefeng.guns.modular.bank.controller;

import cn.afterturn.easypoi.entity.vo.TemplateExcelConstants;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.afterturn.easypoi.view.PoiBaseView;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.aop.Platform;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.BaseModelWarpper;
import com.stylefeng.guns.core.common.annotion.BussinessLog;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.util.DateUtil;
import com.stylefeng.guns.modular.bank.service.IBankService;
import com.stylefeng.guns.modular.system.model.Bank;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 银行管理控制器
 *
 * @author fengshuonan
 * @Date 2018-07-02 11:25:44
 * @author laoyu
 */
@Controller
@RequestMapping("/bank")
public class BankController extends BaseController {

    private String PREFIX = "/bank/bank/";

    @Autowired
    private IBankService bankService;

    /**
     * 跳转到银行管理首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "bank.html";
    }

    /**
     * 跳转到添加银行管理
     */
    @RequestMapping("/bank_add")
    public String bankAdd() {
        return PREFIX + "bank_add.html";
    }

    /**
     * 跳转到期初余额设置
     */
    @RequestMapping("/bank_addBalance")
    public String bank_addBalance() {
        return PREFIX + "bank_addBalance.html";
    }

    /**
     * 跳转到导出页面
     */
    @RequestMapping("/bank_export")
    public String bankExport() {
        return PREFIX + "bank_export.html";
    }

    /**
     * 跳转到修改银行管理
     */
    @RequestMapping("/bank_update/{bankId}")
    public String bankUpdate(@PathVariable Integer bankId, Model model) {
        Bank bank = bankService.selectById(bankId);
        model.addAttribute("item",bank);
        LogObjectHolder.me().set(bank);
        return PREFIX + "bank_edit.html";
    }

    /**
     * 获取银行管理列表
     * @Date 2018-07-02 11:25:44
     * @author laoyu
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@Platform String platform, @RequestParam(required = false) String username,
                       @RequestParam(required = false) String banktype,
                       @RequestParam(required = false) String status, @RequestParam(required = false) String revDate) throws Exception {
        //获取当前操作用户平台
        Page<Bank> page = new PageFactory<Bank>().defaultPage();
        //组装查询
        EntityWrapper<Bank> wrapper = new EntityWrapper<Bank>();
        wrapper.eq("platform", platform);
        //组装查询条件
        if (StringUtils.isNotBlank(username)){
            wrapper.eq("username",username);
        }
        if (StringUtils.isNotBlank(banktype)){
            wrapper.eq("banktype",banktype);
        }
        if (StringUtils.isNotBlank(status)){
            wrapper.eq("status",status);
        }
        if(StringUtils.isNotBlank(revDate)) {
            wrapper.eq("revtime", revDate);
        }else{
            wrapper.ge("revtime", DateUtil.today(0));
        }
        wrapper.orderBy("revtime",false);

        Page<Bank> bankPage = this.bankService.selectPage(page,wrapper);
        //填充字典类型
        bankPage.setRecords((List<Bank>)new BaseModelWarpper(bankPage.getRecords(),Bank.class).warpToObj());
        return  super.packForBT(bankPage);
    }

    /**
     * 描述:合计
     * 创建人: xiang
     * 日期: 2018/8/8
     * 时间: 11:51
     */
    @RequestMapping(value = "tatol")
    @ResponseBody
    public Object tatol(@RequestParam(required = false) String revDate,@Platform String platform
            ,@RequestParam(required = false) String username,
                        @RequestParam(required = false) String banktype,
                        @RequestParam(required = false) String status) throws Exception {
        //组装查询
        EntityWrapper<Bank> wrapper = new EntityWrapper<Bank>();
        wrapper.eq("platform",platform);
        //组装查询条件
        if(StringUtils.isNotBlank(revDate)) {
            wrapper.ge("revtime", revDate);
        }else{
            wrapper.ge("revtime", DateUtil.today(0));
        }
        if (StringUtils.isNotBlank(username))
            wrapper.eq("username",username);
        if (StringUtils.isNotBlank(banktype))
            wrapper.eq("banktype",banktype);
        if (StringUtils.isNotBlank(status))
            wrapper.eq("status",status);

        List<Bank> bankList =this.bankService.selectList(wrapper);
        double bankTotal = 0;//银行总余额
        double incomeAvailable = 0;//入款卡总余额
        double outAvailable = 0;//出款卡总余额
        double mindAvailable = 0;//中转卡总余额
        double incomeFreezing = 0;//入款卡被冻资金
        double outFreezing = 0;//出款卡被冻资金
        double mindFreezing = 0;//中转卡被冻资金
        double incomeBankTotal = 0;//入款银行总余额
        double outBankTotal = 0;//出款银行总余额
        double mindBankTotal = 0;//中转银行总余额
        for (Bank bank : bankList){
            bankTotal +=bank.getBalance();
            if (bank.getBanktype()==Bank.Enum_BankType.入款银行.value){
                incomeBankTotal += bank.getBalance();
                if (bank.getStatus()==Bank.Enum_Status.冻结状态.value)
                    incomeFreezing +=bank.getBalance();
                else
                    incomeAvailable +=bank.getBalance();
            }
            if (bank.getBanktype()==Bank.Enum_BankType.出款银行.value){
                outBankTotal += bank.getBalance();
                if (bank.getStatus()==Bank.Enum_Status.冻结状态.value)
                    outFreezing +=bank.getBalance();
                else
                    outAvailable +=bank.getBalance();
            }
            if (bank.getBanktype()==Bank.Enum_BankType.中转银行.value){
                mindBankTotal += bank.getBalance();
                if (bank.getStatus()==Bank.Enum_Status.冻结状态.value)
                    mindFreezing +=bank.getBalance();
                else
                    mindAvailable +=bank.getBalance();
            }

        }
        Map<String,Object> sumMap = new HashMap<>();
        java.text.DecimalFormat df = new java.text.DecimalFormat("#,###.##");
        sumMap.put("available",df.format(incomeAvailable+outAvailable+mindAvailable));
        sumMap.put("freezing",df.format(mindFreezing+outFreezing+incomeFreezing));
        sumMap.put("bankTotal",df.format(bankTotal));
        sumMap.put("incomeAvailable",df.format(incomeAvailable));
        sumMap.put("outAvailable",df.format(outAvailable));
        sumMap.put("mindAvailable",df.format(mindAvailable));
        sumMap.put("incomeFreezing",df.format(incomeFreezing));
        sumMap.put("outFreezing",df.format(outFreezing));
        sumMap.put("mindFreezing",df.format(mindFreezing));
        sumMap.put("incomeBankTotal",df.format(incomeBankTotal));
        sumMap.put("outBankTotal",df.format(outBankTotal));
        sumMap.put("mindBankTotal",df.format(mindBankTotal));

        return sumMap;
    }

    /**
     * 新增银行管理
     * * @Date 2018-07-02 11:25:44
     *  * @author laoyu
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @BussinessLog(value = "新增银行余额管理")
    public Object add(Bank bank) {
        if (bank.getRevtime()==null) {
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR, "统计时间不能为空");
        }
        if (StringUtils.isBlank(bank.getUsername())) {
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR, "姓名不能为空");
        }
        if (StringUtils.isBlank(bank.getPlatform())) {
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR, "平台名称不能为空");
        }
        if (bank.getBanktype()==null || bank.getStatus()==null) {
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR, "银行类型与状态不能为空");
        }
        if (!bank.getPlatform().equals(ShiroKit.getUser().getDeptcode()))
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"您无权添加该数据，请核对权限");
        bank.setPlatform(ShiroKit.getUser().getDeptcode());
        bank.setCreattime(new Date());
        bank.setUpdatetime(new Date());
        bankService.insert(bank);
        return SUCCESS_TIP;
    }


    /**
     * 设置期初余额
     * * @Date 2018-07-02 11:25:44
     *  * @author laoyu
     */
    @RequestMapping(value = "/addBalance")
    @ResponseBody
    @BussinessLog(value = "设置期初余额")
    public Object addBalance(Bank bank) {
        bank.setBanktype(Bank.Enum_BankType.中转银行.value);
        bank.setStatus(Bank.Enum_Status.启用状态.value);
        if (bank.getRevtime()==null) {
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR, "统计时间不能为空");
        }
        if (bank.getBalance()==null)
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"请设置余额");
        bank.setCreattime(new Date());
        bank.setUsername("期初余额");
        bankService.insert(bank);
        return SUCCESS_TIP;
    }

    /**
     * 删除银行管理
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @BussinessLog(value = "删除银行余额管理")
    public Object delete(@RequestParam Integer bankId) {
        Bank bank = bankService.selectById(bankId);
        if (!bank.getPlatform().equals(ShiroKit.getUser().getDeptcode()))
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"您无权删除该数据，请核对权限");
        bankService.deleteById(bankId);
        return SUCCESS_TIP;
    }

    /**
     * 修改银行管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @BussinessLog(value = "修改银行余额管理")
    public Object update(Bank bank) {
        Bank oldBank = bankService.selectById(bank.getId());
        if (!oldBank.getPlatform().equals(ShiroKit.getUser().getDeptcode()))
            throw new GunsException(BizExceptionEnum.BUSINSS_ERROR,"您无权修改该数据，请核对权限");
        bank.setPlatform(ShiroKit.getUser().getDeptcode());
        bank.setUpdatetime(new Date());
        bankService.updateById(bank);
        return SUCCESS_TIP;
    }

    /**
     * 银行管理详情
     */
    @RequestMapping(value = "/detail/{bankId}")
    @ResponseBody
    public Object detail(@PathVariable("bankId") Integer bankId) {
        return bankService.selectById(bankId);
    }



    /**
     * 批量添加银行
     * @param list
     * @throws GunsException
     */
    public void adds(List<Bank> list) throws GunsException {
        bankService.adds(list);
    }


    /**
     * 描述:下载银行余额表
     * 创建人: laoyu
     * 日期: 2018/8/3 0003
     * 时间: 下午 10:08
     */
    @RequestMapping("exportbank")
    public void exportbank(ModelMap modelMap, HttpServletRequest request,
                           HttpServletResponse response, @RequestParam(required = true) String revtime) {
        Map<String, Object> map = new HashMap<String, Object>();
        TemplateExportParams params = new TemplateExportParams(
                "exceldoc/bank.xlsx");

        map.put("gh", ShiroKit.getUser().getDeptName());
        map.put("revtime", revtime);
        //传入平台 报表时间
        bankService.exportBank(revtime,map);
        modelMap.put(TemplateExcelConstants.FILE_NAME, revtime+ShiroKit.getUser().getDeptName()+"银行第三方余额报表");
        modelMap.put(TemplateExcelConstants.PARAMS, params);
        modelMap.put(TemplateExcelConstants.MAP_DATA, map);
        PoiBaseView.render(modelMap, request, response,
                TemplateExcelConstants.EASYPOI_TEMPLATE_EXCEL_VIEW);

    }
}
